package ltd.newbee.mall.service.impl;

import ltd.newbee.mall.dao.DeliveryFeeConfigMapper;
import ltd.newbee.mall.entity.DeliveryFeeConfig;
import ltd.newbee.mall.service.DeliveryFeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class DeliveryFeeServiceImpl implements DeliveryFeeService {

    @Autowired
    private DeliveryFeeConfigMapper deliveryFeeConfigMapper;

    @Override
    public BigDecimal getDefaultDeliveryFee() {
        DeliveryFeeConfig config = deliveryFeeConfigMapper.selectEnabledConfig();
        if (config != null && config.getEnabled() == 1) {
            return config.getDefaultFee();
        }
        // 如果没有配置，返回默认值0
        return BigDecimal.ZERO;
    }

    @Override
    public DeliveryFeeConfig getDeliveryFeeConfig() {
        return deliveryFeeConfigMapper.selectEnabledConfig();
    }

    @Override
    public boolean updateDeliveryFeeConfig(DeliveryFeeConfig config) {
        if (config == null) {
            return false;
        }

        // 获取当前启用的配置
        DeliveryFeeConfig currentConfig = deliveryFeeConfigMapper.selectEnabledConfig();

        if (currentConfig == null) {
            // 如果没有现有配置，直接插入新配置
            config.setEnabled((byte) 1);
            config.setCreateTime(new Date());
            config.setUpdateTime(new Date());
            return deliveryFeeConfigMapper.insertSelective(config) > 0;
        } else {
            // 如果有现有配置，更新现有配置
            config.setId(currentConfig.getId());
            config.setUpdateTime(new Date());
            return deliveryFeeConfigMapper.updateByPrimaryKeySelective(config) > 0;
        }
    }
}
